﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web.Mvc;

namespace AsscerMVCN2512.Controllers
{
    public class AssetUseController : Controller
    {
        private AssetDBEntities1 db = new AssetDBEntities1();

        // GET: 固定资产使用登记页面
        public ActionResult Index()
        {
            var currentUser = GetCurrentUser();
            if (currentUser == null)
            {
                return RedirectToAction("LoginProject", "EmpolyInfo");
            }

            bool isAdmin = currentUser.RoleID == 1;
            ViewBag.IsAdmin = isAdmin;
            ViewBag.CurrentUserID = currentUser.EmpolyID;

            return View();
        }

        // 获取固定资产使用记录列表
        [HttpPost]
        public JsonResult GetAssetUseList(int page = 1, int limit = 10, string assetDetailNum = "")
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                bool isAdmin = currentUser.RoleID == 1;

                // 基础查询
                var query = from record in db.AssetDetailRecordInfo
                            join detail in db.AssetDetailInfo on record.AssetDetailID equals detail.AssetDetailID
                            join asset in db.AssetInfo on detail.AssetID equals asset.AssetID
                            join empoly in db.EmpolyInfo on record.EmpolyID equals empoly.EmpolyID
                            join area in db.AreaInfo on record.AreaID equals area.AreaID
                            select new
                            {
                                record,
                                detail,
                                asset,
                                empoly,
                                area
                            };

                // 权限控制：普通员工只能查看自己的记录
                if (!isAdmin)
                {
                    query = query.Where(x => x.record.EmpolyID == currentUser.EmpolyID);
                }

                // 搜索条件 - 只保留资产编号搜索
                if (!string.IsNullOrEmpty(assetDetailNum))
                {
                    query = query.Where(x => x.detail.AssetDetailNum.Contains(assetDetailNum));
                }

                // 获取总数
                int totalCount = query.Count();

                // 分页数据
                var list = query
                    .OrderByDescending(x => x.record.AssetDetailRecordUseDate)
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .Select(x => new
                    {
                        AssetDetailRecordID = x.record.AssetDetailRecordID,
                        AssetDetailNum = x.detail.AssetDetailNum,
                        AssetName = x.asset.AssetName,
                        EmpolyName = x.empoly.EmpolyName,
                        AreaName = x.area.AreaName,
                        AssetNum = x.record.AssetNum,
                        AssetDetailRecordUseDate = x.record.AssetDetailRecordUseDate,
                        AssetDetailRecordReturnDate = x.record.AssetDetailRecordReturnDate,
                        AssetDetailRecordReMark = x.record.AssetDetailRecordReMark ?? "暂无",
                        CanReturn = x.record.AssetDetailRecordReturnDate == null // 可以归还的条件
                    })
                    .ToList();

                return Json(new
                {
                    code = 0,
                    msg = "success",
                    count = totalCount,
                    data = list
                });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "查询失败：" + ex.Message });
            }
        }
        [HttpPost]
        public JsonResult ReturnAsset(int assetDetailRecordID)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        // 1. 获取使用记录并锁定
                        var record = db.AssetDetailRecordInfo
                            .FirstOrDefault(r => r.AssetDetailRecordID == assetDetailRecordID);

                        if (record == null)
                        {
                            return Json(new { code = 1, msg = "记录不存在" });
                        }

                        // 2. 权限检查
                        if (currentUser.RoleID != 1 && record.EmpolyID != currentUser.EmpolyID)
                        {
                            return Json(new { code = 1, msg = "没有权限归还此资产" });
                        }

                        // 3. 检查是否已归还
                        if (record.AssetDetailRecordReturnDate != null)
                        {
                            return Json(new { code = 1, msg = "该资产已归还" });
                        }

                        // 4. 获取资产明细
                        var assetDetail = db.AssetDetailInfo
                            .FirstOrDefault(d => d.AssetDetailID == record.AssetDetailID);

                        if (assetDetail == null)
                        {
                            return Json(new { code = 1, msg = "资产明细不存在" });
                        }

                        // 5. 更新使用记录
                        record.AssetDetailRecordReturnDate = DateTime.Now;
                        db.Entry(record).State = EntityState.Modified;

                        // 6. 更新资产明细状态 - 避免外键约束
                        assetDetail.AssetDetailUseState = 0; // 未使用
                        assetDetail.AssetDetailReturnDate = DateTime.Now;
                        // 注意：不要直接设置EmpolyID和AreaID为0，如果数据库不允许
                        // assetDetail.EmpolyID = null; // 如果允许NULL
                        // assetDetail.AreaID = null;   // 如果允许NULL

                        db.Entry(assetDetail).State = EntityState.Modified;

                        // 7. 保存更改
                        db.SaveChanges();
                        transaction.Commit();

                        return Json(new { code = 0, msg = "资产归还成功" });
                    }
                    catch (DbUpdateException dbEx)
                    {
                        transaction.Rollback();
                        // 记录详细的数据库错误
                        var innerException = dbEx.InnerException?.Message ?? dbEx.Message;
                        System.Diagnostics.Debug.WriteLine($"数据库更新异常: {innerException}");
                        return Json(new { code = 1, msg = "归还失败，数据库约束冲突" });
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        System.Diagnostics.Debug.WriteLine($"归还异常: {ex.Message}");
                        return Json(new { code = 1, msg = "归还失败，请稍后重试" });
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"外层异常: {ex.Message}");
                return Json(new { code = 1, msg = "系统异常，请联系管理员" });
            }
        }

        // 获取当前用户
        private EmpolyInfo GetCurrentUser()
        {
            try
            {
                if (Session["user"] != null)
                {
                    var sessionUser = Session["user"] as EmpolyInfo;
                    if (sessionUser != null)
                    {
                        return db.EmpolyInfo.Find(sessionUser.EmpolyID);
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}